import axios  from 'axios';
import {setLocalStorageWithExpiry , getLocalStorageWithExpiry} from '../stor/index.js'
import {useTokenStore} from '../stor/token.js'
import { ElMessage } from 'element-plus';

//const token = getLocalStorageWithExpiry("token");
//使用pinia存储token

const apiClient = axios.create({
  baseURL: '/api', // 开发环境下，代理会处理这个前缀
  timeout: 60000,
  headers:{//请求头，可以加上toekn等内容
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
  },
  validateStatus(status){ //后端返回的状态码，是可选的参数，也可以不加
    return status == 200 ? true : false;
  }
});

//请求拦截器
 apiClient.interceptors.request.use((config)=>{
   // 设置消息头类型
    if(config.contenttype){
      config.headers['Content-Type']=config.contenttype;
    }
    const tokenStore = useTokenStore();
    const token = tokenStore.token;
    //添加token
    if (token) {
        config.headers.Authorization =token;//`${token}`;
      }
    return config;
} , (error)=>{
    console.log(error)
    Promise.reject(error)
})
//没登录时，先跳转到登录
// import { useRouter } from 'vue-router';
// const router = useRouter();
import router from '@/router'
//响应拦截器
apiClient.interceptors.response.use((response)=>{
    //响应成功
    const res = response.data;
    if(res.code ===401 ){
      ElMessage({
        showClose: true,
        message: "登录过期，请重新登录",
      });
      //localStorage.removeItem("token");
      const tokenStore = useTokenStore();
      tokenStore.removeToken();
    }
    return Promise.resolve(res)
} , (error)=>{
    const tokenStore = useTokenStore();
    tokenStore.removeToken();
    if(error.response.status === 401){
      ElMessage.error('请登录');
      router.push('/login');
    }else{
      ElMessage.error('服务异常');
    }
    //响应失败
    let msg = {
        message:'no data',
        data:'none'
    }
    return Promise.reject(msg)
})
 
export default apiClient;